<?php
namespace app\company\controller;

use think\Db;
use think\Exception;
use think\Request;
use PhpOffice\PhpSpreadsheet\IOFactory;

class Role extends Base{

    public function _initialize()
    {
        parent::_initialize();
    }

    public function index(){
        $where['com_id'] = $this->com_id;
        $list = model("Roles")
            ->where($where)
            ->field(["id","name"])
            ->paginate('',false,page_param());
        $this->assign(compact("list"));
        return $this->fetch();
    }

    public function create(Request $request){
        if($request->isPost()){
            return $this->store($request);
        }
        $list = [];
        $this->assign(compact("list"));
        return $this->fetch();
    }

    public function edit(Request $request){
        if($request->isPost()){
            return $this->store($request);
        }
        $params = [
            "id"    =>  input("route.id/d",0),
        ];
        $info = model("Roles")->get($params["id"]);
        $where= [
            "role_id"   =>  $params["id"],
        ];
        $list = model("RolePermissionRelation")->where($where)->column("permission_id");
        $this->assign(compact("info","list"));
        return $this->fetch('create');
    }

    private function store(Request $request){
        $params = $request->only([
            "id","name","relation"
        ],"post");
        $permissionValidate =   model("Role","validate");
        if(!$permissionValidate->scene("store")->check($params)){
            return $this->ajaxReturn(1,$permissionValidate->getError());
        }
        Db::startTrans();
        try {
            $role = model("Roles");
            $data = [
                "id"    =>  $params["id"],
                "name"  =>  $params["name"],
                "com_id"  =>  $this->com_id
            ];
            //判断是否重名
            $where_roles['com_id'] = $this->com_id;
            $where_roles['name'] = $params["name"];
            $where_roles['id'] = ['neq',$params['id']];
            $list = M('com_roles')->where($where_roles)->find();
            if(!empty($list)){
                return $this->ajaxReturn(1,'该名称已被使用');
            }
            if($params["id"]){
                $role->isUpdate(true)->save($data);
                $roleId =   $params["id"];
                model("RolePermissionRelation")
                    ->where("role_id", $roleId)
                    ->delete();
            }else{
                //判断是否重名
                $where_roles['com_id'] = $this->com_id;
                $where_roles['name'] = $params["name"];
                $list = M('com_roles')->where($where_roles)->find();
                if(!empty($list)){
                    return $this->ajaxReturn(1,'该名称已被使用');
                }
                $roleId =   $role->insertGetId($data);
            }
            $addArr = [];
            if (!empty($params["relation"])) {
                foreach ($params["relation"] as $v) {
                    $v = intval($v);
                    if ($v) {
                        $addArr[] = [
                            "role_id" => $roleId,
                            "permission_id" => $v,
                            "u_time"  => date("Y-m-d H:i:s"),
                            "com_id"  => $this->com_id,
                        ];
                    }
                }
            }
            if ( !empty($addArr) ) {
                model("RolePermissionRelation")->saveAll($addArr);
            }
            Db::commit();
        }catch (Exception $e){
            Db::rollback();
            return $this->ajaxReturn(1,"操作失败，请刷新重试");
        }
        return $this->ajaxReturn(0,"", url(CONTROLLER_NAME."/index"));
    }

    public function delete(){
        $params =   [
            "id"    =>  input("post.id/d",0),
        ];
        model("Roles")->where("id",$params["id"])->delete();
        return $this->ajaxReturn();
    }

    //导入
    public function role_import()
{
    if($_FILES['file']['error'] != 0){
        return $this->ajaxReturn(1, "文件上传有误");
    }
    //文件是否大于2M
    if($_FILES['file']['size'] > 102400*5){
        return $this->ajaxReturn(1, "文件最大5M");
    }
    $r = action('file/controller_up');
    if($r['err'] != 0){
        return $this->ajaxReturn(1, "文件保存出错");
    }
    $path = ROOT_PATH.'public'.$r['data']['saveName'];
    $type = 'Xlsx';//设置为Xls代表支持2003或以下版本，Xlsx代表2007版
    $xlsReader = IOFactory::createReader($type);
    $xlsReader->setReadDataOnly(true);
    $Sheets = $xlsReader->load($path);
    $dataArray = $Sheets->getSheet(0)->toArray();
    unlink($path);
    unset($dataArray[0]);       //删除第一行，从第二行开始读取
    unset($dataArray[1]);       //删除第二行，从第三行开始读取
    //企业所有的角色
    $role_ids = M('com_roles')->where(['com_id'=>$this->com_id])->column('id');
    $job_number_ids = M('users')->where(['com_id'=>$this->com_id])->column('job_number');
    $user_ids = M('users')->where(['com_id'=>$this->com_id])->column('id','job_number');
//        var_dump($user_ids);die;
    $err_msg = '';
    $data = [];
    foreach ($dataArray as $key=>$row){
        $index = $key + 1;
        if(!empty($row[0])) {
            //字段验证
            if (empty($row[0])||empty($row[1])||empty($row[2])||empty($row[3])){
                $err_msg .= '第'.$index.'行数据缺失';
            }
            //查询角色id是否存在
            if(!in_array($row[0],$role_ids)){
                $err_msg .= '第'.$index.'行数据角色id不存在';
            }
            //查询用户是否存在
            if(!in_array($row[3],$job_number_ids)){
                $err_msg .= '第'.$index.'行数据用户不存在';
            }
            $data[] = [
                'id'=>$user_ids[$row[3]]??0,
                'role_id'=>$row[0]
            ];
        }
    }
    if(!empty($err_msg)){
        return $this->ajaxReturn(1,$err_msg);
    }else{
        DB::startTrans();
        try{
            if(!empty($data)){
                dbSaveAll($data, 'users', 'id');
            }
            DB::commit();
            return $this->ajaxReturn(0,'导入成功');
        }catch (\Exception $e){
            DB::rollback();
            return $this->ajaxReturn(1,$e->getMessage());
        }
    }
}

}
